package translate

import (
	"encoding/json"
	"ginDemo/vloc"
	"github.com/gin-gonic/gin"
	"github.com/sirupsen/logrus"
)

type Resp struct {
	Msg         string `json:"msg"`
	Translation string `json:"translation"`
}

func respWithMsg(msg string) Resp {
	return Resp{Msg: msg}
}

func Handler(c *gin.Context) {
	req := vloc.Req{}
	if err := c.ShouldBindJSON(&req); err != nil {
		c.JSON(401, respWithMsg("参数错误"))
		return
	}
	reqString, _ := json.Marshal(req)
	logrus.Infof("[translate_handler]-req=%s", string(reqString))
	body, err := json.Marshal(req)
	if err != nil {
		c.JSON(500, respWithMsg("翻译请求构建失败"))
		return
	}

	sending(c, err, body)

}

func sending(c *gin.Context, err error, body []byte) {
	client := vloc.TranslateClient()
	resp, _, err := client.Json("TranslateText", nil, string(body))
	logrus.Infof("[sending]-获取到resp: %s", string(resp))
	if err != nil {
		c.JSON(500, respWithMsg("翻译失败"))
		return
	}
	respMap := make(map[string]any)
	err = json.Unmarshal(resp, &respMap)
	list := respMap["TranslationList"].([]any)
	translationList := list[0].(map[string]any)
	translationResult := translationList["Translation"]
	c.JSON(200, Resp{Msg: "翻译成功", Translation: translationResult.(string)})
}
